﻿using Benefactor.Jobs;
using Benefactor.Services.Repositories;
using Bigway.Common.Jobs;
using Bigway.Common.Logging;
using Extensions.Hosting.AsyncInitialization;
using FluentScheduler;

namespace Benefactor;

public class Initializer(IProductTypeRepository productTypeRepository,
    IBenefitsCardOrderStatusRepository benefitsCardOrderStatusRepository,
    JobRegistryProvider jobRegistryProvider,
    IServiceScopeFactory serviceScopeFactory,
    ILogger<IBackgroundJob> logger
    ) : IAsyncInitializer
{
    public async Task InitializeAsync(CancellationToken cancellationToken)
    {
        var jobRegistry = new JobRegistry(serviceScopeFactory);
        jobRegistryProvider.JobRegisty = jobRegistry;
        JobManager.Initialize(jobRegistry);
        JobManager.JobException += info => logger.LogError(AppLogEvents.BackgroundJob, info.Exception, "An error just happened with a scheduled job: {JobName}", info.Name);
        await productTypeRepository.InitializeAllAsync(cancellationToken);
        await benefitsCardOrderStatusRepository.InitializeAllAsync(cancellationToken);
    }
}